package com.dr.photoedit;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.dr.photoedit.utils.Constants;
import com.dr.photoedit.utils.ImageUtils;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class EditPhotoActivity extends AppCompatActivity {

    ImageView iv;
    TextView mPath;
    String imagePath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_photo);
        iv = (ImageView) findViewById(R.id.img);
        mPath = (TextView) findViewById(R.id.img_path);
        mPath.setText(getIntent().getStringExtra(Constants.CAMERA_PATH));
        Bitmap resultBitmap =  ImageUtils.createBitmapFromPath(Constants.imagePath, this);
        iv.setImageBitmap(resultBitmap);

        //Picasso.with(this).load(new File(Constants.imagePath)).memoryPolicy(MemoryPolicy.NO_CACHE).into(iv);


        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        iv.measure(w, h);
        int height = iv.getMeasuredHeight();
        int width = iv.getMeasuredWidth();
        Log.e("bgmp1==========", resultBitmap.getWidth()+ "+====" + resultBitmap.getHeight());
        Log.e("bgmp0==========", width+ "+====" + height);

    }

    //去涂鸦
    public void onDrawBase(View view) {
        GraffitiActivity.startActivityForResult(this, Constants.imagePath, Constants.REQUEST_CODE_GRAFFITI);
    }

    //去文字
    public void onAddText(View view) {
        Intent photoFrameIntent = new Intent(this, AddTextActivity.class);
        photoFrameIntent.putExtra("camera_path", Constants.imagePath);
        startActivityForResult(photoFrameIntent, Constants.REQUEST_CODE_ADDTEXT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case Constants.REQUEST_CODE_GRAFFITI:
                    onGraffitiResult(data);
                    break;
                case Constants.REQUEST_CODE_ADDTEXT:
                    onAddTextResult(data);
                    break;
            }
        } else {
            Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
        }
    }

    //涂鸦返回
    private void onGraffitiResult(Intent data) {
        String path = data.getStringExtra(GraffitiActivity.KEY_IMAGE_PATH);
        if (TextUtils.isEmpty(path)) {
            return;
        }
        Picasso.with(this).load(new File(Constants.imagePath)).memoryPolicy(MemoryPolicy.NO_CACHE).into(iv);
        mPath.setText(path);
    }

    //文字返回
    private void onAddTextResult(Intent data) {
        String resultPath = data.getStringExtra("camera_path");
        Bitmap resultBitmap =  ImageUtils.createBitmapFromPath(resultPath, this);
        //Bitmap resultBitmap = BitmapFactory.decodeFile(resultPath);
        //pictureShow.setImageBitmap(resultBitmap);
        iv.setImageBitmap(resultBitmap);

        //Picasso.with(this).load(new File(Constants.imagePath)).memoryPolicy(MemoryPolicy.NO_CACHE).into(iv);
        mPath.setText(resultPath);
    }

    /**
     * 根据路径获取图片资源（已缩放）
     */
    private Bitmap getBitmapFromUrl(String url, double width, double height) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true; // 设置了此属性一定要记得将值设置为false
        Bitmap bitmap = BitmapFactory.decodeFile(url);
        // 优化
        options.inJustDecodeBounds = false;
        int mWidth = bitmap.getWidth();
        int mHeight = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth = 1;
        float scaleHeight = 1;

        // 按照固定宽高进行缩放
        if (mWidth <= mHeight) {
            scaleWidth = (float) (width / mWidth);
            scaleHeight = (float) (height / mHeight);
        } else {
            scaleWidth = (float) (height / mWidth);
            scaleHeight = (float) (width / mHeight);
        }
        // 按照固定大小对图片进行缩放
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, mWidth, mHeight, matrix, true);
        // 回收
        bitmap.recycle();
        return newBitmap;
    }


    /**
     * 存储缩放的图片
     */
    private void saveScalePhoto(Bitmap bitmap) {
        // 照片全路径
        String fileName = "";
        // 文件夹路径
        String pathUrl = Environment.getExternalStorageDirectory().getPath() + "/Test/";
        //namePic = "p" + DateFormat.format("hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";

        //机型 + 批架次 +专业 + 时间
        // String name = DateFormat.format("yyyyMMddhhmmss", Calendar.getInstance(Locale.CHINA))+ ".jpg";
        String name = "Test" + ".jpg";
        FileOutputStream fos = null;
        File file = new File(pathUrl);
        Log.d("文件夹", pathUrl);
        file.mkdirs();// 创建文件夹
        fileName = pathUrl + name;
        try {
            fos = new FileOutputStream(fileName);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
